﻿Imports System.Collections.ObjectModel

Namespace Coding4Fun.PrinterDisplayHack
	''' <summary>
	''' Interaction logic for FindPrinters.xaml
	''' </summary>
	Partial Public Class FindPrinters
		Inherits Window

		Public Property SelectedIpAddress() As String

		Public Property Printers() As ObservableCollection(Of LocalPrinter)
			Get
				Return CType(GetValue(PrintersProperty), ObservableCollection(Of LocalPrinter))
			End Get
			Set(ByVal value As ObservableCollection(Of LocalPrinter))
				SetValue(PrintersProperty, value)
			End Set
		End Property
		Public Shared ReadOnly PrintersProperty As DependencyProperty = DependencyProperty.Register("Printers", GetType(ObservableCollection(Of LocalPrinter)), GetType(FindPrinters), New UIPropertyMetadata(Nothing))


		Public Sub New()
			InitializeComponent()

			LocatePrinters()
		End Sub

		Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			Me.Close()
		End Sub

		Private Sub btnRefresh_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			LocatePrinters()
		End Sub

		Private Sub ListView_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
			If e.AddedItems.Count > 0 Then
				Dim lstSelected As LocalPrinter = CType(e.AddedItems(0), LocalPrinter)

				If lstSelected IsNot Nothing Then
					SelectedIpAddress = lstSelected.Address.ToString()
					Me.btnSelect.IsEnabled = True
				End If
			End If
		End Sub

		Private Sub ListView_MouseDoubleClick(ByVal sender As Object, ByVal e As MouseButtonEventArgs)
			If e.Source IsNot Nothing Then
				CloseWithSelection()
			End If
		End Sub

		Private Sub btnSelect_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
			CloseWithSelection()
		End Sub

		Private Sub LocatePrinters()
			Me.btnSelect.IsEnabled = False
			SelectedIpAddress = ""

			Printers = New ObservableCollection(Of LocalPrinter)()

			Dim tmpList As List(Of LocalPrinter) = PrinterUtils.GetPrinters()

			For Each printer As LocalPrinter In tmpList
				Me.Printers.Add(printer)
			Next printer
		End Sub

		Private Sub CloseWithSelection()
			If Not String.IsNullOrWhiteSpace(SelectedIpAddress) Then
				Me.DialogResult = True
				Me.Close()
			End If
		End Sub
	End Class
End Namespace
